package io.renren.modules.wap.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.redis.RedisUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.commons.dynamic.datasource.annotation.DataSource;
import io.renren.modules.wap.dao.ExternalConfigDao;
import io.renren.modules.wap.dto.ExternalConfigDTO;
import io.renren.modules.wap.entity.ExternalConfigEntity;
import io.renren.modules.wap.service.ExternalConfigService;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 对接三方配置类
 *
 * @author Liang Pei 
 * @since 1.0.0 2025-01-02
 */
@Service
@DataSource("wap")
public class ExternalConfigServiceImpl extends CrudServiceImpl<ExternalConfigDao, ExternalConfigEntity, ExternalConfigDTO> implements ExternalConfigService {

    @Autowired
    private RedisUtils redisUtils;

    private static final String EXTERNAL_CONFIG_KEY = "admin:config:external";

    @Override
    public QueryWrapper<ExternalConfigEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<ExternalConfigEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
    public ExternalConfigEntity getConfigByQueryId(String queryId) {
        //先走缓存
        ExternalConfigEntity configEntity = null;
        Object o = redisUtils.hGet(EXTERNAL_CONFIG_KEY, queryId);
        if (ObjectUtil.isNotEmpty(o)) {
            configEntity = JSON.parseObject(o.toString(), ExternalConfigEntity.class);
        } else {
            configEntity = baseDao.selectOne(new QueryWrapper<ExternalConfigEntity>()
                    .eq("query_id", queryId));
            if (configEntity != null) {
                // 放入redis
                redisUtils.hSet(EXTERNAL_CONFIG_KEY, queryId, JSON.toJSONString(configEntity));
            }
        }
        return configEntity;
    }
}